//20. 有效的括号
//用栈来实现此问题

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>

typedef char STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;		// 栈顶
	int capacity;  // 容量 
}Stack;

void StackInit(Stack* ps)
{
	assert(ps);

	ps->a = NULL;
	//ps->top = -1;//top 指栈顶数据
	ps->top = 0;//top 指栈顶数据的下一个位置
	ps->capacity = 0;
}

// 检测栈是否为空，如果为空返回非零结果，如果不为空返回0 
int StackEmpty(Stack* ps)
{
	assert(ps);

	if (0 == ps->top)
		return 1;
	else
		return 0;
}

// 入栈 
void StackPush(Stack* ps, STDataType data)
{
	assert(ps);

	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail:");
			return;
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}

	ps->a[ps->top] = data;
	ps->top++;
}

// 出栈 
void StackPop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	ps->top--;
}

// 获取栈顶元素 
STDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	return ps->a[ps->top - 1];
}

// 获取栈中有效元素个数 
int StackSize(Stack* ps)
{
	assert(ps);

	return ps->top;
}

// 销毁栈 
void StackDestroy(Stack* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}


bool isValid(char* s) {
	Stack st;
	StackInit(&st);

	while (*s)
	{
		//1.是左括号就存放在栈里
		//2.拿出左括号与右括号作比较
		if (*s == '(' ||
			*s == '[' ||
			*s == '{')
		{
			StackPush(&st, *s);
		}
		else
		{
			if (StackEmpty(&st))//第一个就是右括号就说明出错，销毁栈并返回false
			{
				StackDestroy(&st);
				return false;
			}

			char top = StackTop(&st);//取出栈顶元素
			StackPop(&st);//出栈
			if (top == '(' && *s != ')'
				|| top == '[' && *s != ']'
				|| top == '{' && *s != '}')//左右括号不匹配
			{
				StackDestroy(&st);//销毁栈
				return false;//返回false
			}
		}
		s++;
	}

	bool ret = StackEmpty(&st);//循环完后栈不是空就是错误
	StackDestroy(&st);//销毁栈

	return ret;//返回ret
}